﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Xml;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Security.Cryptography;
using BSF.Db;
using BSF.Log;
using BSF.SystemConfig;
using BSF.Tool;
using HuntingFishGame.Domain.Model.WeChat;
using WeBSF.ToolComm;

namespace HuntingFishGame.Domain.BLL.WeChat
{
    public class PubBLL
    {
        #region 接收消息
        /// <summary>接收信息</summary>
        /// <param name="InputStream"></param>
        /// <returns></returns>
        public static PostMessage Receive(System.IO.Stream InputStream)
        {
            PostMessage pm = new PostMessage();
            try
            {
                XmlDocument xml = new XmlDocument();
                xml.Load(InputStream);
                pm.ToUserName = xml.GetElementsByTagName("ToUserName")[0].InnerText;
                pm.FromUserName = xml.GetElementsByTagName("FromUserName")[0].InnerText;
                pm.CreateTime = Convert.ToInt32(xml.GetElementsByTagName("CreateTime")[0].InnerText);
                pm.MsgType = xml.GetElementsByTagName("MsgType")[0].InnerText;
                switch (pm.MsgType)
                {
                    case "text":
                        pm.Content = xml.GetElementsByTagName("Content")[0].InnerText;
                        pm.MsgId = xml.GetElementsByTagName("MsgId")[0].InnerText;//pm.MsgId = Convert.ToInt64(xml.GetElementsByTagName("MsgId")[0].InnerText);  //事件没有MsgId
                        break;
                    case "image":
                        pm.PicUrl = xml.GetElementsByTagName("PicUrl")[0].InnerText;
                        pm.MediaId = xml.GetElementsByTagName("MediaId")[0].InnerText;
                        pm.MsgId = xml.GetElementsByTagName("MsgId")[0].InnerText;//pm.MsgId = Convert.ToInt64(xml.GetElementsByTagName("MsgId")[0].InnerText);  //事件没有MsgId
                        break;
                    case "voice":
                        pm.Format = xml.GetElementsByTagName("Format")[0].InnerText;
                        pm.MediaId = xml.GetElementsByTagName("MediaId")[0].InnerText;
                        pm.MsgId = xml.GetElementsByTagName("MsgId")[0].InnerText;//pm.MsgId = Convert.ToInt64(xml.GetElementsByTagName("MsgId")[0].InnerText);  //事件没有MsgId
                        break;
                    case "video":
                        pm.MediaId = xml.GetElementsByTagName("MediaId")[0].InnerText;
                        pm.ThumbMediaId = xml.GetElementsByTagName("ThumbMediaId")[0].InnerText;
                        pm.MsgId = xml.GetElementsByTagName("MsgId")[0].InnerText;//pm.MsgId = Convert.ToInt64(xml.GetElementsByTagName("MsgId")[0].InnerText);  //事件没有MsgId
                        break;
                    case "location":
                        pm.Location_X = Convert.ToDecimal(xml.GetElementsByTagName("Location_X")[0].InnerText);
                        pm.Location_Y = Convert.ToDecimal(xml.GetElementsByTagName("Location_Y")[0].InnerText);
                        pm.Scale = xml.GetElementsByTagName("Scale")[0].InnerText;
                        pm.Label = xml.GetElementsByTagName("Label")[0].InnerText;
                        pm.MsgId = xml.GetElementsByTagName("MsgId")[0].InnerText;//pm.MsgId = Convert.ToInt64(xml.GetElementsByTagName("MsgId")[0].InnerText);  //事件没有MsgId
                        break;
                    case "link":
                        pm.Title = xml.GetElementsByTagName("Title")[0].InnerText;
                        pm.Description = xml.GetElementsByTagName("Description")[0].InnerText;
                        pm.Url = xml.GetElementsByTagName("Url")[0].InnerText;
                        pm.MsgId = xml.GetElementsByTagName("MsgId")[0].InnerText;//pm.MsgId = Convert.ToInt64(xml.GetElementsByTagName("MsgId")[0].InnerText);  //事件没有MsgId
                        break;
                    case "event":
                        //pm.Event = xml.GetElementsByTagName("Event")[0].InnerText;
                        //pm.EventKey = xml.GetElementsByTagName("EventKey")[0].InnerText;
                        GetEvent(xml, out pm);
                        break;
                    default:
                        break;
                }
                return pm;
            }
            catch (Exception ex)
            {
                ErrorLog.Write("消息序列化失败:" + ex.Message, ex);
                return pm;
            }
        }
        private static void GetEvent(XmlDocument xml, out PostMessage pm)
        {
            pm = new PostMessage();
            pm.ToUserName = xml.GetElementsByTagName("ToUserName")[0].InnerText;//开发者微信号 
            pm.FromUserName = xml.GetElementsByTagName("FromUserName")[0].InnerText;//发送方帐号（一个OpenID）
            pm.CreateTime = Convert.ToInt32(xml.GetElementsByTagName("CreateTime")[0].InnerText);//消息创建时间 （整型） 
            pm.MsgType = xml.GetElementsByTagName("MsgType")[0].InnerText;//消息类型，event 
            pm.Event = xml.GetElementsByTagName("Event")[0].InnerText;
            #region 接收事件消息
            var evt = xml.GetElementsByTagName("Event")[0].InnerText.ToLower();
            switch (evt)
            {
                case "click"://点击菜单拉取消息时的事件推送 
                    {
                        pm.EventKey = xml.GetElementsByTagName("EventKey")[0].InnerText;
                        break;
                    }
                case "view"://点击菜单跳转链接时的事件推送 
                    {
                        pm.EventKey = xml.GetElementsByTagName("EventKey")[0].InnerText;
                        break;
                    }
                case "location"://上报地理位置事件
                    {
                        pm.Latitude = xml.GetElementsByTagName("Latitude")[0].InnerText;//地理位置纬度
                        pm.Longitude = xml.GetElementsByTagName("Longitude")[0].InnerText;//地理位置经度
                        pm.Precision = xml.GetElementsByTagName("Precision")[0].InnerText;//地理位置精度
                        break;
                    }
                case "scan"://用户已关注时的事件推送
                    {
                        pm.EventKey = xml.GetElementsByTagName("EventKey")[0].InnerText;
                        pm.Ticket = xml.GetElementsByTagName("Ticket")[0].InnerText;
                        break;
                    }
                case "unsubscribe"://取消订阅
                    break;
                case "subscribe":
                    {
                        XmlNodeList elemList = xml.GetElementsByTagName("Ticket");
                        if (elemList.Count > 0)//用户未关注时，进行关注后的事件推送
                        {
                            pm.EventKey = xml.GetElementsByTagName("EventKey")[0].InnerText;//事件KEY值，qrscene_为前缀，后面为二维码的参数值
                            pm.Ticket = xml.GetElementsByTagName("Ticket")[0].InnerText;//二维码的ticket，可用来换取二维码图片
                        }
                        else
                        {
                            //订阅
                        }
                        break;
                    }
                //自定义菜单事件
                case "scancode_push"://扫码推事件的事件推送
                    {
                        break;
                    }
                case "scancode_waitmsg"://扫码推事件且弹出“消息接收中”提示框的事件推送
                    {
                        break;
                    }
                case "pic_sysphoto"://弹出系统拍照发图的事件推送
                    {
                        break;
                    }
                case "pic_photo_or_album"://弹出拍照或者相册发图的事件推送
                    {
                        break;
                    }
                case "pic_weixin"://弹出微信相册发图器的事件推送
                    {
                        break;
                    }
                case "location_select"://弹出地理位置选择器的事件推送
                    {
                        break;
                    }
            }
            #endregion
        }
        #endregion

        #region 发送被动响应消息
        /// <summary>回复文字</summary>
        /// <param name="toUser"></param>
        /// <param name="fromUser"></param>
        /// <param name="CreateTime"></param>
        /// <param name="Content"></param>
        /// <param name="FuncFlag"></param>
        /// <returns></returns>
        public static string ReplyText(string toUser, string fromUser, DateTime CreateTime, string Content)
        {
            //Content = System.Web.HttpUtility.UrlEncode(Content, System.Text.Encoding.UTF8);
            //Content = System.Web.HttpUtility.UrlEncode(Content, System.Text.Encoding.GetEncoding("GB2312"));
            string sendxml = "<xml>" +
                             "<ToUserName><![CDATA[" + toUser + "]]></ToUserName>" +
                             "<FromUserName><![CDATA[" + fromUser + "]]></FromUserName>" +
                             "<CreateTime>" + LibConvert.DateTimeToInt(CreateTime) + "</CreateTime>" +
                             "<MsgType><![CDATA[text]]></MsgType>" +
                             "<Content><![CDATA[" + Content + "]]></Content>" +
                             "</xml>";
            return sendxml;
        }

        /// <summary>回复图片</summary>
        /// <param name="toUser">接收方帐号（收到的OpenID）</param>
        /// <param name="fromUser">开发者微信号</param>
        /// <param name="CreateTime">消息创建时间 （整型） </param>
        /// <param name="MediaId">通过上传多媒体文件，得到的id。</param>
        /// <returns></returns>
        public static string ReplyImage(string toUser, string fromUser, DateTime CreateTime, string MediaId)
        {
            string sendxml = "<xml>" +
                             "<ToUserName><![CDATA[" + toUser + "]]></ToUserName>" +
                             "<FromUserName><![CDATA[" + fromUser + "]]></FromUserName>" +
                             "<CreateTime>" + LibConvert.DateTimeToInt(CreateTime) + "</CreateTime>" +
                             "<MsgType><![CDATA[image]]></MsgType>" +
                             "<Image>" +
                             "<MediaId><![CDATA[" + MediaId + "]]></MediaId>" +
                             "<Image>" +
                             "</xml>";
            return sendxml;
        }

        /// <summary>回复语音消息</summary>
        /// <param name="toUser">接收方帐号（收到的OpenID）</param>
        /// <param name="fromUser">开发者微信号</param>
        /// <param name="CreateTime">消息创建时间戳（整型）</param>
        /// <param name="MsgType">语音，voice</param>
        /// <param name="MediaId">通过上传多媒体文件，得到的id</param>
        /// <returns></returns>
        public static string ReplyVoice(string toUser, string fromUser, DateTime CreateTime, string MediaId)
        {
            string sendxml = "<xml>" +
                             "<ToUserName><![CDATA[" + toUser + "]]></ToUserName>" +
                             "<FromUserName><![CDATA[" + fromUser + "]]></FromUserName>" +
                             "<CreateTime>" + LibConvert.DateTimeToInt(CreateTime).ToString() + "</CreateTime>" +
                             "<MsgType><![CDATA[voice]]></MsgType>" +
                             "<Voice>" +
                             "<MediaId><![CDATA[" + MediaId + "]]></MediaId>" +
                             "</Voice>" +
                             "</xml>";
            return sendxml;
        }

        /// <summary>回复视频消息</summary>
        /// <param name="toUser">接收方帐号（收到的OpenID）</param>
        /// <param name="fromUser">开发者微信号</param>
        /// <param name="CreateTime">消息创建时间戳（整型）</param>
        /// <param name="MsgType">视频，video</param>
        /// <param name="MediaId">通过上传多媒体文件，得到的id</param>
        /// <param name="Title">视频消息的标题</param>
        /// <param name="Description">视频消息的描述</param>
        /// <returns></returns>
        public static string ReplyVideo(string toUser, string fromUser, DateTime CreateTime, string MediaId, string Title, string Description)
        {
            string sendxml = "<xml>" +
                             "<ToUserName><![CDATA[" + toUser + "]]></ToUserName>" +
                             "<FromUserName><![CDATA[" + fromUser + "]]></FromUserName>" +
                             "<CreateTime>" + LibConvert.DateTimeToInt(CreateTime).ToString() + "</CreateTime>" +
                             "<MsgType><![CDATA[video]]></MsgType>" +
                             "<Video>" +
                             "<MediaId><![CDATA[" + MediaId + "]]></MediaId>" +
                             "<Title><![CDATA[" + Title + "]]></Title>" +
                             "<Description><![CDATA[" + Description + "]]></Description>" +
                             "</Video>" +
                             "</xml>";
            return sendxml;
        }

        /// <summary>回复音乐消息</summary>
        /// <param name="toUser"></param>
        /// <param name="fromUser"></param>
        /// <param name="CreateTime"></param>
        /// <param name="Title"></param>
        /// <param name="Description"></param>
        /// <param name="MusicUrl"></param>
        /// <param name="HQMusicUrl"></param>
        /// <param name="MediaId"></param>
        /// <returns></returns>
        public static string ReplyMusic(string toUser, string fromUser, DateTime CreateTime, string Title, string Description, string MusicUrl, string HQMusicUrl, string MediaId)
        {
            string sendxml = "<xml>" +
                             "<ToUserName><![CDATA[" + toUser + "]]></ToUserName>" +
                             "<FromUserName><![CDATA[" + fromUser + "]]></FromUserName>" +
                             "<CreateTime>" + LibConvert.DateTimeToInt(CreateTime).ToString() + "</CreateTime>" +
                             "<MsgType><![CDATA[music]]></MsgType>" +
                             "<Music>" +
                             "<Title><![CDATA[" + Title + "]]></Title>" +
                             "<Description><![CDATA[" + Description + "]]></Description>" +
                             "<MusicUrl><![CDATA[" + MusicUrl + "]]></MusicUrl>" +
                             "<HQMusicUrl><![CDATA[" + HQMusicUrl + "]]></HQMusicUrl>" +
                             "<ThumbMediaId><![CDATA[" + MediaId + "]]></ThumbMediaId>" +
                             "</Music>" +
                             "</xml>";
            return sendxml;
        }

        /// <summary>回复图文</summary>
        /// <param name="toUser"></param>
        /// <param name="fromUser"></param>
        /// <param name="CreateTime"></param>
        /// <param name="Articles"></param>
        /// <returns></returns>
        public static string ReplyNews(string toUser, string fromUser, DateTime CreateTime, List<ReplyNewsArticle> Articles)
        {
            string sendxml = "<xml>" +
                             "<ToUserName><![CDATA[" + toUser + "]]></ToUserName>" +
                             "<FromUserName><![CDATA[" + fromUser + "]]></FromUserName>" +
                             "<CreateTime>" + LibConvert.DateTimeToInt(CreateTime).ToString() + "</CreateTime>" +
                             "<MsgType><![CDATA[news]]></MsgType>" +
                             "<ArticleCount>" + Articles.Count.ToString() + "</ArticleCount>" +
                             "<Articles>";
            foreach (ReplyNewsArticle rna in Articles)
            {
                sendxml = sendxml + "<item>" +
                            "<Title><![CDATA[" + rna.Title + "]]></Title>" +
                            "<Description><![CDATA[" + rna.Description + "]]></Description>" +
                            "<PicUrl><![CDATA[" + rna.PicUrl + "]]></PicUrl>" +
                            "<Url><![CDATA[" + rna.Url + "]]></Url>" +
                            "</item>";
            }
            sendxml = sendxml + "</Articles>" +
                             "</xml>";
            return sendxml;
        }
        #endregion

        #region 主动发送客服消息
        /// <summary>
        /// 把发送的消息转到多客服系统
        /// </summary>
        /// <param name="toUser"></param>
        /// <param name="fromUser"></param>
        /// <param name="CreateTime"></param>
        /// <returns></returns>
        public static string DKFReplyNews(string toUser, string fromUser, DateTime CreateTime)
        {
            string sendxml = "<xml>";
            sendxml = string.Concat(sendxml, "<ToUserName><![CDATA[" + toUser + "]]></ToUserName>");
            sendxml = string.Concat(sendxml, "<FromUserName><![CDATA[" + fromUser + "]]></FromUserName>");
            sendxml = string.Concat(sendxml, "<CreateTime>" + LibConvert.DateTimeToInt(CreateTime).ToString() + "</CreateTime>");
            sendxml = string.Concat(sendxml, "<MsgType><![CDATA[transfer_customer_service]]></MsgType>");
            sendxml = string.Concat(sendxml, "</xml>");
            return sendxml;
        }

        /// <summary>
        /// 主动给用户发消息（用户）
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="appId"></param>
        /// <param name="appSecret"></param>
        /// <returns>errcode=0为成功</returns>
        public static ReturnCodeModel SendMsg(SendMsg _model, string AccessToken, List<SendMsg> msg = null)
        {
            string url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=";
            url = url + AccessToken;
            var json = string.Empty;
            switch (_model.msgtype)
            {
                case "text":
                    json = SendText(_model.touser, _model.text);
                    break;
                case "image":
                    json = SendImage(_model.touser, _model.media_id);
                    break;
                case "voice":
                    json = SendVoice(_model.touser, _model.media_id);
                    break;
                case "video":
                    json = SendVideo(_model.touser, _model.media_id, _model.thumb_media_id, _model.title, _model.description);
                    break;
                case "music":
                    json = SendMusic(_model.touser, _model.media_id, _model.thumb_media_id, _model.title, _model.description, _model.hqmusicurl);
                    break;
                case "news":
                    json = SendArticles(_model.touser, msg);
                    break;
            }

            var retJson = PostAndGetHelper.HttpPost2(url, json);
            return JsonHelper.JsonTo<ReturnCodeModel>(retJson);
        }

        /// <summary>发送文字</summary>
        /// <param name="touser">普通用户openid </param>
        /// <param name="msgtype">消息类型，text </param>
        /// <param name="content">文本消息内容 </param>
        /// <returns></returns>
        public static string SendText(string touser, string content)
        {
            string sendxml = "{" +
                             "\"touser\":\"" + touser + "\"," +
                             "\"msgtype\":\"text\"," +
                             "\"text\":{" +
                             "\"content\":\"" + content + "\"" +
                             "}}";
            return sendxml;
        }

        /// <summary>发送图片</summary>
        /// <param name="touser">普通用户openid </param>
        /// <param name="msgtype">消息类型，image </param>
        /// <param name="media_id">发送的图片的媒体ID </param>
        /// <returns></returns>
        public static string SendImage(string touser, string media_id)
        {
            string sendxml = "{" +
                             "\"touser\":\"" + touser + "\"," +
                             "\"msgtype\":\"image\"," +
                             "\"image\":{" +
                             "\"media_id\":\"" + media_id + "\"" +
                             "}}";
            return sendxml;
        }

        /// <summary>发送语音</summary>
        /// <param name="touser">普通用户openid </param>
        /// <param name="msgtype">消息类型，image </param>
        /// <param name="media_id">发送的语音的媒体ID </param>
        /// <returns></returns>
        public static string SendVoice(string touser, string media_id)
        {
            string sendxml = "{" +
                             "\"touser\":\"" + touser + "\"," +
                             "\"msgtype\":\"voice\"," +
                             "\"voice\":{" +
                             "\"media_id\":\"" + media_id + "\"" +
                             "}}";
            return sendxml;
        }

        /// <summary>发送视频</summary>
        /// <param name="touser">普通用户openid </param>
        /// <param name="msgtype">消息类型，video </param>
        /// <param name="media_id">发送的图片的媒体ID </param>
        /// <returns></returns>
        public static string SendVideo(string touser, string media_id, string thumb_media_id, string title, string description)
        {
            string sendxml = "{" +
                             "\"touser\":\"" + touser + "\"," +
                             "\"msgtype\":\"video\"," +
                             "\"video\":{" +
                             "\"media_id\":\"" + media_id + "\"," +
                             "\"thumb_media_id\":\"" + thumb_media_id + "\"," +
                             "\"title\":\"" + title + "\"," +
                             "\"description\":\"" + description + "\"" +
                             "}}";
            return sendxml;
        }

        /// <summary>发送音乐</summary>
        /// <param name="touser">普通用户openid </param>
        /// <param name="msgtype">消息类型，music </param>
        /// <param name="media_id">发送的图片的媒体ID </param>
        /// <returns></returns>
        public static string SendMusic(string touser, string media_id, string thumb_media_id, string title, string description, string hqmusicurl)
        {
            string sendxml = "{" +
                             "\"touser\":\"" + touser + "\"," +
                             "\"msgtype\":\"music\"," +
                             "\"music\":{" +
                             "\"title\":\"" + title + "\"," +
                             "\"description\":\"" + description + "\"," +
                             "\"hqmusicurl\":\"" + hqmusicurl + "\"," +
                             "\"thumb_media_id\":\"" + thumb_media_id + "\"" +
                             "}}";
            return sendxml;
        }

        /// <summary>发送图文</summary>
        /// <param name="touser">普通用户openid </param>
        /// <param name="msgtype">消息类型，news </param>
        /// <param name="media_id">发送的语音的媒体ID </param>
        /// <returns></returns>
        public static string SendArticles(string touser, List<SendMsg> media_id)
        {
            string temparticles = string.Empty;
            foreach (var _obj in media_id)
            {
                temparticles += "{" +
                                 "\"title\":\"" + _obj.title + "\"," +
                                 "\"description\":\"" + _obj.description + "\"," +
                                 "\"url\":\"" + _obj.url + "\"," +
                                 "\"picurl\":\"" + _obj.picurl + "\"" +
                                "},";
            }
            string sendxml = "{" +
                             "\"touser\":\"" + touser + "\"," +
                             "\"msgtype\":\"news\"," +
                             "\"news\":{" +
                             "\"articles\":[" + temparticles.TrimEnd(',') + "]" +
                             "}}";
            return sendxml;
        }

        #endregion

        #region 群发（与多媒体文件接口关联）

        /// <summary>
        /// 根据分组进行群发
        /// </summary>
        /// <param name="mess"></param>
        /// <param name="appId"></param>
        /// <param name="appSecret"></param>
        /// <returns></returns>
        public static SendReturnCodeModelModel SendMessByGroup(FilterMess mess, string AccessToken, bool is_to_all = false)
        {
            var json = string.Empty;//var json = mess.GetJSON();//var json = Utility.ToJson(mess);
            string filter = string.Empty;
            if (is_to_all)
            {
                filter = "{\"is_to_all\":true},";
            }
            else
            {
                filter = "{\"is_to_all\":false,\"group_id\":\"" + mess.group_id + "\"},";
            }
            switch (mess.msgtype)
            {
                case "mpnews"://图文消息（注意图文消息的media_id需要通过上传图文消息素材的接口来得到）
                    json = "{\"filter\":" + filter +
                            "\"mpnews\":" +
                            "{\"media_id\":\"" + mess.media_id + "\"}," +
                            "\"msgtype\":\"mpnews\"" +
                            "}";
                    break;
                case "text"://文本
                    json = "{\"filter\":" + filter +
                            "\"text\":" +
                            "{\"content\":\"" + mess.content + "\"}," +
                            "\"msgtype\":\"text\"" +
                            "}";
                    break;
                case "voice"://语音（注意此处media_id需通过基础支持中的上传下载多媒体文件来得到）
                    json = "{\"filter\":" + filter +
                            "\"voice\":" +
                            "{\"media_id\":\"" + mess.media_id + "\"}," +
                            "\"msgtype\":\"voice\"" +
                            "}";
                    break;
                case "image"://图片（注意此处media_id需通过基础支持中的上传下载多媒体文件来得到）
                    json = "{\"filter\":" + filter +
                            "\"image\":" +
                            "{\"media_id\":\"" + mess.media_id + "\"}," +
                            "\"msgtype\":\"image\"" +
                            "}";
                    break;
                case "mpvideo"://请注意，此处视频的media_id需通过POST请求到下述接口特别地得到： https://file.api.weixin.qq.com/cgi-bin/media/uploadvideo?access_token=ACCESS_TOKEN POST数据如下（此处media_id需通过基础支持中的上传下载多媒体文件来得到）
                    json = "{\"filter\":" + filter +
                            "\"mpvideo\":" +
                            "{\"media_id\":\"" + mess.media_id + "\"}," +
                            "\"msgtype\":\"mpvideo\"" +
                            "}";
                    break;
            }
            var _model = SendMessByGroup(json, AccessToken);
            return _model;
        }

        /// <summary>
        /// 根据分组进行群发
        /// </summary>
        /// <param name="mess"></param>
        /// <param name="appId"></param>
        /// <param name="appSecret"></param>
        /// <returns></returns>
        public static SendReturnCodeModelModel SendMessByGroup(string messJSON, string AccessToken)
        {
            var url = "https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token=";
            url = url + AccessToken;
            var retJson = PostAndGetHelper.HttpPost2(url, messJSON);
            return JsonHelper.JsonTo<SendReturnCodeModelModel>(retJson);
        }

        //返回数据示例（正确时的JSON返回结果）：
        //{
        //   "errcode":0,
        //   "errmsg":"send job submission success",
        //   "msg_id":34182
        //}
        /// <summary>
        /// 根据OpenID列表群发
        /// </summary>
        /// <param name="mess"></param>
        /// <param name="appId"></param>
        /// <param name="appSecret"></param>
        /// <returns></returns>
        public static SendReturnCodeModelModel SendMessByUsers(FilterMess mess, string AccessToken)
        {
            var json = string.Empty;//var json = mess.GetJSON();//var json = Utility.ToJson(mess);
            string temptouser = string.Empty;
            foreach (var tempid in mess.openid)
            {
                temptouser = string.Concat(temptouser, "\"", tempid, "\",");
            }
            temptouser = temptouser.TrimEnd(',');//移除最后一个,
            switch (mess.msgtype)
            {
                case "mpnews"://图文消息（注意图文消息的media_id需要通过上述方法来得到）
                    json = "{\"touser\":" +
                            "[" + temptouser + "]," +
                            "\"mpnews\":" +
                            "{\"media_id\":\"" + mess.media_id + "\"}," +
                            "\"msgtype\":\"mpnews\"" +
                            "}";
                    break;
                case "text"://文本
                    json = "{\"touser\":" +
                            "[" + temptouser + "]," +
                            "\"text\":" +
                            "{\"content\":\"" + mess.content + "\"}," +
                            "\"msgtype\":\"text\"" +
                            "}";
                    break;
                case "voice"://语音（注意此处media_id需通过基础支持中的上传下载多媒体文件来得到）
                    json = "{\"touser\":" +
                            "[" + temptouser + "]," +
                            "\"voice\":" +
                            "{\"media_id\":\"" + mess.media_id + "\"}," +
                            "\"msgtype\":\"voice\"" +
                            "}";
                    break;
                case "image"://图片（注意此处media_id需通过基础支持中的上传下载多媒体文件来得到）
                    json = "{\"touser\":" +
                            "[" + temptouser + "]," +
                            "\"image\":" +
                            "{\"media_id\":\"" + mess.media_id + "\"}," +
                            "\"msgtype\":\"image\"" +
                            "}";
                    break;
                case "mpvideo"://请注意，此处视频的media_id需通过POST请求到下述接口特别地得到： https://file.api.weixin.qq.com/cgi-bin/media/uploadvideo?access_token=ACCESS_TOKEN POST数据如下（此处media_id需通过基础支持中的上传下载多媒体文件来得到）
                    json = "{\"touser\":" +
                            "[" + temptouser + "]," +
                            "\"mpvideo\":" +
                            "{\"media_id\":\"" + mess.media_id + "\"}," +
                            "\"msgtype\":\"mpvideo\"" +
                            "}";
                    break;
            }
            var _model = SendMessByUsers(json, AccessToken);
            return _model;
        }

        /// <summary>
        /// 根据OpenID列表群发
        /// </summary>
        /// <param name="mess"></param>
        /// <param name="appId"></param>
        /// <param name="appSecret"></param>
        /// <returns></returns>
        public static SendReturnCodeModelModel SendMessByUsers(string messJSON, string AccessToken)
        {
            var url = "https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token=";
            url = url + AccessToken;
            var retJson = PostAndGetHelper.HttpPost2(url, messJSON);
            return JsonHelper.JsonTo<SendReturnCodeModelModel>(retJson);
        }

        /// <summary>
        /// 删除群发.
        /// 请注意，只有已经发送成功的消息才能删除删除消息只是将消息的图文详情页失效，已经收到的用户，还是能在其本地看到消息卡片。 另外，删除群发消息只能删除图文消息和视频消息，其他类型的消息一经发送，无法删除。
        /// </summary>
        /// <param name="msgid"></param>
        /// <param name="appId"></param>
        /// <param name="appSecret"></param>
        /// <returns></returns>
        public static ReturnCodeModel DeleteMess(int msgid, string AccessToken)
        {
            var url = "https://api.weixin.qq.com//cgi-bin/message/mass/delete?access_token=";
            url = url + AccessToken;
            var json = "{\"msgid\":" + msgid.ToString() + "}";
            var retJson = PostAndGetHelper.HttpPost2(url, json);
            return JsonHelper.JsonTo<ReturnCodeModel>(retJson);
        }

        //事件推送群发结果
        //由于群发任务提交后，群发任务可能在一定时间后才完成，因此，群发接口调用时，仅会给出群发任务是否提交成功的提示，若群发任务提交成功，则在群发任务结束时，会向开发者在公众平台填写的开发者URL（callback URL）推送事件。

        #endregion

        #region 用户分组接口

        /// <summary>
        /// 创建分组
        /// </summary>
        /// <param name="name">分组名字（30个字符以内）</param>
        /// <param name="appId"></param>
        /// <param name="appSecret"></param>
        /// <returns></returns>
        public static GroupInfo CreateGroup(string name, string AccessToken)
        {
            string url = "https://api.weixin.qq.com/cgi-bin/groups/create?access_token=";
            url = url + AccessToken;
            var post = "{\"group\":{\"name\":\"" + name + "\"}}";
            var json = PostAndGetHelper.HttpPost2(url, post);
            if (json.IndexOf("errcode") > 0)
            {
                var gi = new GroupInfo();
                gi.error = JsonHelper.JsonTo<ReturnCodeModel>(json);
                return gi;
            }
            else
            {
                var dict = JsonHelper.JsonTo<Dictionary<string, Dictionary<string, object>>>(json);
                var gi = new GroupInfo();
                var gpdict = dict["group"];
                gi.id = Convert.ToInt32(gpdict["id"]);
                gi.name = gpdict["name"].ToString();
                return gi;
            }
        }

        /// <summary>
        /// 查询所有分组
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="appSecret"></param>
        /// <returns></returns>
        public static Groups GetGroups(string AccessToken)
        {
            string url = "https://api.weixin.qq.com/cgi-bin/groups/get?access_token=";
            url = url + AccessToken;
            string json = PostAndGetHelper.HttpGet2(url);
            if (json.IndexOf("errcode") > 0)
            {
                var gs = new Groups();
                gs.error = JsonHelper.JsonTo<ReturnCodeModel>(json);
                return gs;
            }
            else
            {
                var dict = JsonHelper.JsonTo<Dictionary<string, List<Dictionary<string, object>>>>(json);
                var gs = new Groups();
                var gilist = dict["groups"];
                foreach (var gidict in gilist)
                {
                    var gi = new GroupInfo();
                    gi.name = gidict["name"].ToString();
                    gi.id = Convert.ToInt32(gidict["id"]);
                    gi.count = Convert.ToInt32(gidict["count"]);
                    gs.Add(gi);
                }
                return gs;
            }
        }

        /// <summary>
        /// 修改分组名
        /// </summary>
        /// <param name="id">分组id，由微信分配</param>
        /// <param name="name">分组名字（30个字符以内）</param>
        /// <param name="AccessToken">access_token:调用接口凭证</param>
        /// <returns></returns>
        public static ReturnCodeModel UpdateGroup(string id, string name, string AccessToken)
        {
            string url = "https://api.weixin.qq.com/cgi-bin/groups/update?access_token=";
            url = url + AccessToken;
            var post = "{\"group\":{\"id\":" + id + ",\"name\":\"" + name + "\"}}";
            var json = PostAndGetHelper.HttpPost2(url, post);
            return JsonHelper.JsonTo<ReturnCodeModel>(json);
        }

        /// <summary>
        /// 查询用户所在分组
        /// </summary>
        /// <param name="openid"></param>
        /// <param name="appId"></param>
        /// <param name="appSecret"></param>
        /// <returns></returns>
        public static GroupID GetUserGroup(string openid, string AccessToken)
        {
            string url = "https://api.weixin.qq.com/cgi-bin/groups/getid?access_token=";
            url = url + AccessToken;
            var post = "{\"openid\":\"" + openid + "\"}";
            var json = PostAndGetHelper.HttpPost2(url, post);
            if (json.IndexOf("errcode") > 0)
            {
                var gid = new GroupID();
                gid.error = JsonHelper.JsonTo<ReturnCodeModel>(json);
                return gid;
            }
            else
            {
                var dict = JsonHelper.JsonTo<Dictionary<string, int>>(json);
                var gid = new GroupID();
                gid.id = dict["groupid"];
                return gid;
            }
        }

        /// <summary>
        /// 移动用户分组
        /// </summary>
        /// <param name="openid"></param>
        /// <param name="groupid"></param>
        /// <param name="appId"></param>
        /// <param name="appSecret"></param>
        /// <returns></returns>
        public static ReturnCodeModel MoveGroup(string openid, string groupid, string AccessToken)
        {
            string url = "https://api.weixin.qq.com/cgi-bin/groups/members/update?access_token=";
            url = url + AccessToken;
            var post = "{\"openid\":\"" + openid + "\",\"to_groupid\":" + groupid + "}";
            var json = PostAndGetHelper.HttpPost2(url, post);
            return JsonHelper.JsonTo<ReturnCodeModel>(json);
        }

        /// <summary>
        /// 批量移动用户分组
        /// </summary>
        /// <param name="access_token">调用接口凭证</param>
        /// <param name="openid_list">用户唯一标识符openid的列表（size不能超过50）</param>
        /// <param name="to_groupid">分组id</param>
        /// <returns></returns>
        public static Groups MoveGroup(List<string> openid_list, string to_groupid, string AccessToken)
        {
            string url = "https://api.weixin.qq.com/cgi-bin/groups/members/batchupdate?access_token=";
            url = url + AccessToken;
            var post = "{\"openid_list\":[" + string.Join(",", "\"" + openid_list + "\"") + "],\"to_groupid\":" + to_groupid + "}";
            var json = PostAndGetHelper.HttpPost2(url, post);

            //正常时的返回JSON数据包示例：{"errcode": 0, "errmsg": "ok"}
            var gs = new Groups();
            gs.error = JsonHelper.JsonTo<ReturnCodeModel>(json);
            return gs;
        }

        /// <summary>
        /// 删除分组
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="appSecret"></param>
        /// <returns></returns>
        public static Groups DelGroup(string AccessToken)
        {
            string url = "https://api.weixin.qq.com/cgi-bin/groups/delete?access_token=";
            url = url + AccessToken;
            string json = PostAndGetHelper.HttpGet2(url);

            //正常时的返回JSON数据包示例：{"errcode": 0, "errmsg": "ok"}
            var gs = new Groups();
            gs.error = JsonHelper.JsonTo<ReturnCodeModel>(json);
            return gs;
        }
        #endregion

        #region 用户信息

        /// <summary>
        /// 设置备注名
        /// </summary>
        /// <param name="openid"></param>
        /// <param name="remark"></param>
        /// <param name="AccessToken"></param>
        /// <returns></returns>
        public static string SetUserRemark(string openid, string remark, string AccessToken)
        {
            string url = string.Concat("https://api.weixin.qq.com/cgi-bin/user/info/updateremark?access_token=", AccessToken);
            var data = string.Concat("{ \"openid\":\"", openid, "\", \"remark\":\"", remark, "\" }");
            var json = PostAndGetHelper.HttpPost2(url, data);
            ReturnCodeModel _model = JsonHelper.JsonTo<ReturnCodeModel>(json);
            return _model.GetJSON();
        }

        /// <summary>
        /// 得到用户基本信息
        /// </summary>
        /// <param name="openid"></param>
        /// <param name="lang"></param>
        /// <param name="appId"></param>
        /// <param name="appSecret"></param>
        /// <returns></returns>
        public static string GetUserInfo(string openid, LangType lang, string AccessToken)
        {
            var ui = GetUserInfoObj(openid, lang, AccessToken);
            return ui.GetJSON();
        }
        /// <summary>
        /// 得到用户基本信息
        /// </summary>
        /// <param name="openid"></param>
        /// <param name="lang"></param>
        /// <param name="appId"></param>
        /// <param name="appSecret"></param>
        /// <returns></returns>
        public static UserInfo GetUserInfoObj(string openid, LangType lang, string AccessToken)
        {
            var ui = new UserInfo();
            string url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=";
            url = url + AccessToken + "&openid=" + openid + "&lang=" + lang.ToString();

            var json = PostAndGetHelper.HttpGet2(url);

            if (json.IndexOf("errcode") > 0)
            {
                ui.error = JsonHelper.JsonTo<ReturnCodeModel>(json);
            }
            else
            {
                ui = JsonHelper.JsonTo<UserInfo>(json);
            }
            return ui;
        }

        //获取用户地理位置(上报地理位置事件)
        //网页授权获取用户基本信息//先不做
        //网页获取用户网络状态（JS接口）//先不做

        #endregion

        #region 获取关注者列表

        /// <summary>
        /// 获取关注者列表
        /// </summary>
        /// <param name="next_openid"></param>
        /// <param name="appId"></param>
        /// <param name="appSecret"></param>
        /// <returns></returns>
        public static Followers GetFollowers(string AccessToken, string next_openid = "")
        {
            string url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=";
            url = url + AccessToken;
            if (!string.IsNullOrEmpty(next_openid))
            {
                url = url + "&next_openid=" + next_openid;
            }
            var json = PostAndGetHelper.HttpGet2(url);
            if (json.IndexOf("errcode") > 0)
            {
                var fs = new Followers();
                fs.error = JsonHelper.JsonTo<ReturnCodeModel>(json);
                return fs;
            }
            else
            {
                return JsonHelper.JsonTo<Followers>(json);
            }
        }

        #endregion

        #region 自定义菜单

        /// <summary>
        /// 创建自定义菜单
        /// </summary>
        /// <param name="menuJSON"></param>
        /// <param name="appId"></param>
        /// <param name="appSecret"></param>
        /// <returns></returns>
        public static ReturnCodeModel CreateMenu(string menuJSON, string AccessToken)
        {
            string _url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=";
            _url = _url + AccessToken;
            var _retJson = PostAndGetHelper.HttpPost2(_url, menuJSON);
            return JsonHelper.JsonTo<ReturnCodeModel>(_retJson);
        }

        /// <summary>
        /// 自定义菜单查询接口，直接返回自定义菜单json字符串
        /// </summary>
        public static string GetMenu(string AccessToken)
        {
            string _url = string.Format("https://api.weixin.qq.com/cgi-bin/menu/get?access_token={0}", AccessToken);
            string _json = PostAndGetHelper.HttpGet(_url, string.Empty);
            //var _json = Tencent.PostAndGetHelper.HttpGet2(_url);
            return _json;//返回{"menu":{"button":[{"type":"click","name":"今日歌曲","key":"V1001_TODAY_MUSIC","sub_button":[]}]}}
        }

        /// <summary>
        /// 自定义菜单删除接口
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="appSecret"></param>
        /// <returns></returns>
        public static ReturnCodeModel DeleteMenu(string AccessToken)
        {
            string _url = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=";
            _url = _url + AccessToken;
            var _json = PostAndGetHelper.HttpGet2(_url);
            return JsonHelper.JsonTo<ReturnCodeModel>(_json);
        }
        #endregion

        #region 二维码
        /// <summary>
        /// 创建二维码ticket
        /// </summary>
        /// <param name="isTemp">true:临时二维码ticket,false:永久二维码ticket</param>
        /// <param name="scene_id">二维码场景id</param>
        /// <param name="AccessToken"></param>
        /// <returns></returns>
        public static string GetQRTicket(bool isTemp, int scene_id, string AccessToken)
        {
            var _model = PubBLL.CreateQRCode(isTemp, scene_id, AccessToken);
            return _model.GetJSON();
        }

        /// <summary>
        /// 创建二维码ticket
        /// </summary>
        /// <param name="isTemp"></param>
        /// <param name="scene_id"></param>
        /// <param name="appId"></param>
        /// <param name="appSecret"></param>
        /// <returns></returns>
        public static QRCodeTicket CreateQRCode(bool isTemp, int scene_id, string AccessToken)
        {
            string url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=";
            url = url + AccessToken;
            var action_name = isTemp ? "QR_SCENE" : "QR_LIMIT_SCENE";
            string data;
            if (isTemp)
            {
                data = "{\"expire_seconds\": 1800, \"action_name\": \"QR_SCENE\", \"action_info\": {\"scene\": {\"scene_id\":" + scene_id + "}}}";
            }
            else
            {
                data = "{\"action_name\": \"QR_LIMIT_SCENE\", \"action_info\": {\"scene\": {\"scene_id\": " + scene_id + "}}}";
            }

            var json = PostAndGetHelper.HttpPost2(url, data);
            if (json.IndexOf("ticket") > 0)
            {
                return JsonHelper.JsonTo<QRCodeTicket>(json);
            }
            else
            {
                QRCodeTicket tk = new QRCodeTicket();
                tk.error = JsonHelper.JsonTo<ReturnCodeModel>(json);
                return tk;
            }
        }

        /// <summary>
        /// 通过ticket换取二维码，得到QR图片地址
        /// 测试：http://localhost/weixin/GetQRUrl?qrcodeTicket=gQGh8ToAAAAAAAAAASxodHRwOi8vd2VpeGluLnFxLmNvbS9xL1dFTzJpb0xsYkRRVkNWNDM3MjFFAAIEgtVZVAMECAcAAA==
        /// </summary>
        /// <param name="qrcodeTicket"></param>
        /// <returns></returns>
        public static string GetQRUrl(string qrcodeTicket)
        {
            // 转byte[]然后在转成image
            //var _QRimg = PostAndGetHelper.HttpGetImg("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + System.Web.HttpUtility.HtmlEncode(qrcodeTicket), string.Empty);
            var tup = PostAndGetHelper.HttpGet("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + System.Web.HttpUtility.HtmlEncode(qrcodeTicket));
            var dm = new DownloadFile();
            dm.ContentType = tup.Item2;

            if (tup.Item1 == null)
            {
                dm.error = JsonHelper.JsonTo<ReturnCodeModel>(tup.Item3);
            }
            else
            {
                dm.Stream = tup.Item1;
            }
            #region 保存图片
            string _QRimg = string.Empty;
            //Stream _stream = ConvertHelper.converter.getYCStream("http://himg2.huanqiu.com/attachment/081104/55c7e57181.jpg");
            //根目录路径，相对路径
            String rootPath = BSFConfig.QRImage + DirectoryHelper.CreateFilePath() + "/";
            String dirPath = System.Web.HttpContext.Current.Server.MapPath(rootPath);
            string filename = DirectoryHelper.CreateFileName() + ".jpg";
            DirectoryHelper.CreateDirectory(dirPath);

            Dictionary<string, string> dict = new Dictionary<string, string>();
            dict.Add("dirpath", dirPath);
            dict.Add("filename", filename);
            dict.Add("relativepath", rootPath + filename);
            //ConvertHelper.converter.SaveYCStream(dm.Stream, dict);//保存图片
            //先创建路径
            DirectoryHelper.CreateDirectory(dict["dirpath"].ToString());
            ConvertHelper.converter.WriteFile(dm.Stream, dict["dirpath"].ToString() + dict["filename"].ToString());//保存文件
            _QRimg = dict["relativepath"].ToString();
            #endregion
            return _QRimg;
        }
        #endregion

        #region 多媒体文件
        /// <summary>
        /// 上传视频,用于群发
        /// </summary>
        /// <param name="videoInfo"></param>
        /// <param name="AccessToken"></param>
        /// <returns></returns>
        public static MediaInfo UploadVideoForMess(UploadVideoInfo videoInfo, string AccessToken)
        {
            var url = "https://file.api.weixin.qq.com/cgi-bin/media/uploadvideo?access_token=";
            url = url + AccessToken;
            var json = PostAndGetHelper.HttpPost2(url, JsonHelper.ToJson(videoInfo));
            if (json.IndexOf("errcode") > 0)
            {
                var mi = new MediaInfo();
                mi.error = JsonHelper.JsonTo<ReturnCodeModel>(json);
                return mi;
            }
            else
            {
                return JsonHelper.JsonTo<MediaInfo>(json);
            }
        }

        /// <summary>
        /// 上传图文消息素材,用于群发
        /// </summary>
        /// <param name="news"></param>
        /// <returns></returns>
        public static MediaInfo UploadArticles(Articles list, string AccessToken)
        {
            string url = "https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token=";
            url = url + AccessToken;
            var json = PostAndGetHelper.HttpPost2(url, JsonHelper.ToJson(list));
            if (json.IndexOf("errcode") > 0)
            {
                var mi = new MediaInfo();
                mi.error = JsonHelper.JsonTo<ReturnCodeModel>(json);
                return mi;
            }
            else
            {
                return JsonHelper.JsonTo<MediaInfo>(json);
            }
        }

        /// <summary>
        /// 上传图文消息素材,用于群发
        /// </summary>
        /// <param name="articles"></param>
        /// <param name="AccessToken"></param>
        /// <returns>返回上传图文后的media_id</returns>
        public static string SetArticles(List<FilterMess> articles, string AccessToken)
        {
            string jsonText = "{ \"articles\": [";
            if (articles.Count > 0)
            {
                int count = 1;
                foreach (var tempobj in articles)
                {
                    jsonText = string.Concat(jsonText, "{",
                            "\"thumb_media_id\":\"" + tempobj.thumb_media_id + "\",",
                            "\"author\":\"" + tempobj.author + "\",",
                            "\"title\":\"" + tempobj.title + "\",",
                            "\"content_source_url\":\"" + tempobj.content_source_url + "\",",
                            "\"content\":\"" + tempobj.content + "\",",
                            "\"digest\":\"" + tempobj.digest + "\",",
                            "\"show_cover_pic\":\"" + tempobj.show_cover_pic + "\"",
                            "}");
                    if (count < articles.Count)
                        jsonText += ",";
                    count++;
                }
            }
            //不管‘,’是不是在最后，都移除1个‘,’所以还是要用jsonText.TrimEnd(',')
            //if (jsonText.LastIndexOf(",") > 0)
            //    jsonText = jsonText.Remove(jsonText.LastIndexOf(","), 1);
            jsonText = string.Concat(jsonText.TrimEnd(','), "]}");
            var url = "https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token=";
            url = url + AccessToken;
            var retJson = PostAndGetHelper.HttpPost2(url, jsonText);

            JObject jo = (JObject)JsonConvert.DeserializeObject(retJson); //JObject.Parse(jsonText);
            //正确时返回：{"type":"news","media_id":"t2yPfLrs5a-n8ErTfslaDJL6AiB_0uVINLCCn-sMYSwrWsSxSYQdfefimYCt7dmd","created_at":1416468815}
            string media_id = string.Empty;
            if (jo.Property("media_id") == null || jo.Property("media_id").ToString() == "")
            { }
            else media_id = jo["media_id"].ToString();

            return media_id;
            //返回数据示例（正确时的JSON返回结果）：
            //{
            //   "type":"news",
            //   "media_id":"CsEf3ldqkAYJAU6EJeIkStVDSvffUJ54vqbThMgplD-VJXXof6ctX5fI6-aYyUiQ",
            //   "created_at":1391857799
            //}
        }

        /// <summary>
        /// 上传多媒体文件
        /// </summary>
        /// <param name="file"></param>
        /// <param name="type"> 媒体文件类型,image,voice,video,thumb,news</param>
        /// <param name="appId"></param>
        /// <param name="appSecret"></param>
        /// <returns></returns>
        public static string UploadMedia(string file, string type, string AccessToken)
        {
            var mi = new MediaInfo();
            string url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=";
            url = url + AccessToken + "&type=" + type.ToString();
            var json = PostAndGetHelper.HttpUpload(url, file);
            if (json.IndexOf("errcode") > 0)
            {
                mi.error = JsonHelper.JsonTo<ReturnCodeModel>(json);
            }
            else
            {
                mi = JsonHelper.JsonTo<MediaInfo>(json);
            }
            return mi.GetJSON();
        }

        /// <summary>
        /// 下载多媒体文件
        /// </summary>
        /// <param name="media_id"></param>
        /// <param name="appId"></param>
        /// <param name="appSecret"></param>
        /// <returns></returns>
        public static string DownloadMedia(string media_id, string AccessToken)
        {
            string url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=";
            url = url + AccessToken + "&media_id=" + media_id;
            var tup = PostAndGetHelper.HttpGet(url);
            var dm = new DownloadFile();
            dm.ContentType = tup.Item2;

            if (tup.Item1 == null)
            {
                dm.error = JsonHelper.JsonTo<ReturnCodeModel>(tup.Item3);
            }
            else
            {
                dm.Stream = tup.Item1;
                #region 保存图片等多媒体文件
                //Stream _stream = ConvertHelper.converter.getYCStream("http://himg2.huanqiu.com/attachment/081104/55c7e57181.jpg");
                //根目录路径，相对路径
                String rootPath = BSFConfig.DownloadFile + DirectoryHelper.CreateFilePath() + "/";
                String dirPath = System.Web.HttpContext.Current.Server.MapPath(rootPath);
                string[] contenttypesplit = dm.ContentType.Split('/');
                string extension = contenttypesplit[contenttypesplit.Length - 1];
                //switch(extension)
                //{
                //    case "amr":
                //        extension = "mp3";//amr文件保存成mp3
                //        break;
                //}
                string filename = DirectoryHelper.CreateFileName() + "." + extension;
                DirectoryHelper.CreateDirectory(dirPath);

                Dictionary<string, string> dict = new Dictionary<string, string>();
                dict.Add("dirpath", dirPath);
                dict.Add("filename", filename);
                dict.Add("relativepath", rootPath + filename);
                //ConvertHelper.converter.SaveYCStream(dm.Stream, dict);//保存图片
                //先创建路径
                DirectoryHelper.CreateDirectory(dict["dirpath"].ToString());
                ConvertHelper.converter.WriteFile(dm.Stream, dict["dirpath"].ToString() + dict["filename"].ToString());//保存文件
                string retString = dict["relativepath"].ToString();
                dm.filepath = retString;
                #endregion
                #region 转换成mp3
                if (extension.ToLower().Equals("amr"))
                {
                    try
                    {
                        bool ret = FileHelper.ConvertMp3(System.Web.HttpContext.Current.Server.MapPath(retString), System.Web.HttpContext.Current.Server.MapPath(retString.ToLower().Replace(".amr", ".mp3")));
                        if (ret)
                        {
                            dm.filepath = retString.ToLower().Replace(".amr", ".mp3");
                            FileHelper.FileDel(retString);//删除原来的amr文件
                        }
                    }
                    catch { }
                }
                #endregion
            }
            //数据流保存成多媒体文件，然后返回文件路径
            return dm.filepath; //return dm.GetJSON();
        }

        #endregion

        #region C# 的时间戳转换
        /// <summary>
        /// 时间戳转为C#格式时间
        /// </summary>
        /// <param name="timeStamp">Unix时间戳格式</param>
        /// <returns>C#格式时间</returns>
        public static DateTime GetTime(string timeStamp)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(timeStamp + "0000000");
            TimeSpan toNow = new TimeSpan(lTime);
            return dtStart.Add(toNow);
        }

        /// <summary>
        /// DateTime时间格式转换为Unix时间戳格式
        /// </summary>
        /// <param name="time"> DateTime时间格式</param>
        /// <returns>Unix时间戳格式</returns>
        public static int ConvertDateTimeInt(System.DateTime time)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            return (int)(time - startTime).TotalSeconds;
        }
        #endregion

    }
}
